package com.lemon.boot.common.service.impl;

import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendBatchCardSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendBatchSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.lemon.boot.common.enums.SmsTemplateCodeEnum;
import com.lemon.boot.common.properties.SmsConfigProperties;
import com.lemon.boot.common.service.SmsService;
import com.lemon.boot.common.thread.pool.ExecutorThreadPoolGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author 李猛
 * @datetime 2024/7/19 9:09
 * @description 短信服务实现类
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {
    @Resource
    private SmsConfigProperties smsConfigProperties;

    @Override
    public boolean asyncSend(String phone, Map<String, String> templateParam, SmsTemplateCodeEnum templateCode) {
        //1.创建客户端
        final Client client = createClient();

        //2.短信请求
        final SendSmsRequest request = sendSmsRequest(phone, templateParam, templateCode);

        //3.异步发送短信
        CompletableFuture<Boolean> asyncMessage = CompletableFuture.supplyAsync(() -> {
            try {
                //3.发送短信
                SendSmsResponse response = client.sendSmsWithOptions(request, new RuntimeOptions());
                log.info("短信发送结果：{}", response.getBody().toString());
                return "OK".equals(response.getBody().getCode());
            } catch (Exception e) {
                log.error("短信发送失败：{}", e.getMessage());
                return false;
            }
        }, ExecutorThreadPoolGroup.messageExecutorService);

        //4.返回结果
        try {
            return asyncMessage.get();
        } catch (InterruptedException | ExecutionException e) {
            log.error("短信发送失败：{}", e.getMessage());
            return false;
        }
    }

    @Override
    public boolean syncSend(String phone, Map<String, String> templateParam, SmsTemplateCodeEnum templateCode) {
        //1.创建客户端
        final Client client = createClient();

        //2.短信请求
        final SendSmsRequest request = sendSmsRequest(phone, templateParam, templateCode);

        try {
            //3.发送短信
            SendSmsResponse response = client.sendSmsWithOptions(request, new RuntimeOptions());
            log.info("短信发送结果：{}", response.getBody().toString());
            return "OK".equals(response.getBody().getCode());
        } catch (Exception e) {
            log.error("短信发送失败：{}", e.getMessage());
            return false;
        }
    }

    /**
     * 创建客户端
     *
     * @return
     * @throws Exception
     */
    private Client createClient() {
        try {
            return new Client(smsConfigProperties.getConfig());
        } catch (Exception e) {
            log.error("阿里云短信配置信息异常：{}", e.getMessage());
            throw new RuntimeException();
        }
    }

    /**
     * 创建单条的请求
     *
     * @param phone
     * @param templateParam
     * @return
     */
    private SendSmsRequest sendSmsRequest(String phone, Map<String, String> templateParam, SmsTemplateCodeEnum templateCode) {
        return new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName(smsConfigProperties.getSignName())
                .setTemplateCode(templateCode.getTemplateCode())
                .setTemplateParam(JSONUtil.toJsonStr(templateParam));
    }
}
